#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Skripta za generisanje preporucenih meceva. Pokrece se kao cron job
"""

################# bootstrap djanga ##################################
import os
import sys
from random import choice
sys.path.append(os.path.dirname(sys.argv[0]) + "/../../")

from django.core.management import setup_environ
from mdcssport import settings
setup_environ(settings)
#####################################################################

import datetime
import random

from django.template import loader, Context
from django.core.mail import EmailMessage

from mdcssport.mdcsapp.models import Match, PlayerUserProfile

def generate_recommended(game_type):
    today = datetime.date.today()
    if today.weekday() == 5 or today.weekday() == 6:
        return
    yesterday = datetime.date.today() - datetime.timedelta(days=1)
    if yesterday.weekday() < 5:
        last_recommended_day = yesterday
    else:
        last_recommended_day = datetime.date.today() - datetime.timedelta(days=3)

    # uzmi one usere koji su za recommended i one koji nisu juce bili za recommended
    users = PlayerUserProfile.objects.all()
    if game_type == 1:
        users = users.filter(chess_recommended=True)
    elif game_type == 2:
        users = users.filter(tf_recommended=True)
    else:
        return
    users = list(users)

    played_last_recommended_day = Match.objects.filter(date_generated = last_recommended_day).filter(game_type=game_type)
    for match in played_last_recommended_day:
        for user in match.home.all():
            if user in users:
                users.remove(user)
        for user in match.away.all():
            if user in users:
                users.remove(user)

    generated_rm = []
    for i in range(4):
        users_needed = 2 if game_type == 1 else 4
        if len(users) < users_needed:
            break
        home_users = []
        for j in range(users_needed/2):
            user = choice(users)
            home_users.append(user)
            users.remove(user)
        away_users = []
        for j in range(users_needed/2):
            user = choice(users)
            away_users.append(user)
            users.remove(user)
        
        rm = Match()
        rm.game_type = game_type
        rm.date_generated = today
        rm.save()
        rm.home = home_users
        rm.away = away_users
        generated_rm.append(rm)

    # saljemo mailove
    for rm in generated_rm:
        all_users = list(rm.home.all()) + list(rm.away.all())
        all_user_mail = [user.user.email for user in all_users if user.send_mail==True and user.user.email != ""]
        if len(all_user_mail) > 0:
            template = loader.get_template("mail/recommended_picked.html")
            message_text = template.render(Context({"rm": rm }))
            msg = EmailMessage("[mdcs-sport] Imate preporučen meč danas", message_text,
                "mdcs-sport-no-reply@sport.mdcs.rs", all_user_mail)
            msg.content_subtype = "html"
            msg.send(fail_silently = False)

if __name__ == '__main__':
    generate_recommended(1)
    generate_recommended(2)